package chances.epg.navigator.controller.data;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import chances.epg.entity.biz.Biz;
import chances.epg.navigator.AccessException;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.controller.AccessController;
import chances.epg.navigator.template.TemplateConfig;
import chances.epg.navigator.template.TemplateContext;


/**
 * 展示频道导航.
 * @author Elysium
 *
 */
@Controller
public class BizPageController extends AccessController {
	/**
	 * 展示频道页面.
	 * @param model
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/api/page/{bizCode}") 
    public String list(ModelMap model, HttpServletRequest request,HttpServletResponse response) throws IOException {
		AccessContext context = accessContextFactory.createAccessContext(request);
		
		//检查bizcode
		Biz biz = this.getCurBiz(context);
		if(biz == null) {
			logger.error("biz not found,access uri:{}",request.getRequestURI());
			throw new AccessException(AccessException.ACC_BIZ_NOT_FOUND,"biz not found,biz code:" + context.getBizCode());
		}
		context.setBiz(biz);
		
		//
		if(StringUtils.isNotBlank(biz.getExternalUrl())){
			this.redirectExternalUrl(request, response, context, biz.getExternalUrl());
			return null;
		}else if(StringUtils.isNotBlank(biz.getRefBizCode())){
			this.redirectBiz(context, request,response, biz.getRefBizCode());
			return null;
		}else{
			//查找模板
			TemplateConfig templateConfig = this.templateConfigService.getSelfTemplateConfig(context.getBizCode());
			if(templateConfig == null) {
				logger.debug("find template from parent biz.");
				templateConfig = this.getTemplateConfigOfParent(biz);
			}
			
			if(templateConfig == null) {
				logger.error("not found tempalte for biz,access uri:{}",request.getRequestURI());
				throw new AccessException(AccessException.ACC_TEMPLATE_NOT_FOUND,"not found template for biz:" + context.getBizCode());
			}
			
			TemplateContext templateContext = this.templateConfigService.createTemplateContext(templateConfig, context);
			
			//设置上下文参数.
			this.setAccessContext(model, request, context);
			this.setTemplateContext(model, request, templateContext,context);
			
			logger.debug("find template for uri:{},template file path:{}",new Object[]{request.getRequestURI(),templateContext.getTemplateFilePath()});
			return templateContext.getTemplateFilePath();
		}
	}
	
}
